The Thread Manager provides a single, cooperative method of scheduling threads. In cooperative scheduling, a thread must explicitly yield control to give other threads an opportunity to run.
Previously, the Thread Manager supported preemptive scheduling as well as cooperative scheduling but currently only cooperative scheduling is supported.
The situation for threads within an application is similar to that of applications in a multitasking environment. Every application must have periodic yielding calls that allow the Process Manager to schedule other applications as necessary--for example, when a user presses the mouse button to select another application to run. Likewise, every thread within an application must make regular yield calls to allow other threads to run. The Thread Manager provides the following functions to yield control to other threads:
As you can see from the three calls that yield control from the current thread, there are two ways to determine the next thread to run. One way is for you to specify a particular thread to run next; the other way is to allow the Thread Manager to choose the next available thread to run. (An available thread is one that is marked ready to run--an unavailable thread is one that is marked stopped.) The Thread Manager queues up all of the threads that are ready to run, and, when a nonspecific yield occurs, it executes the next available thread. When a thread finishes executing, it moves to the back of the queue if it is still ready to run, or, if it is marked as stopped, the Thread Manager removes it from the queue of available threads.
Note
The previous paragraph describes the default Thread Manager scheduling mechanism. You can also define a custom scheduler for your application that works in conjunction with the default scheduling mechanism to determine the next thread to run. See Custom Scheduler for more information about creating a custom scheduler for your application.
Figure 2 shows the default Thread Manager scheduling model.
Figure 2 Thread scheduling model
Because threads yield control under explicit conditions, they have access to all Toolbox and Operating System routines. They allow you do anything that you can currently do in an application without threads, such as allocate memory, perform file I/O, perform QuickDraw operations, and so on.
For situations in which you are concerned about the integrity of your data, the Thread Manager provides a pair of functions, ThreadBeginCritical and ThreadEndCritical , that enable you to mark a section of code as critical, turning scheduling off. With scheduling off, the Thread Manager does not allow any threads to be scheduled until scheduling is turned back on; that is, all yield and other scheduling functions are ignored until the code exits the critical section. See Turning Scheduling Off for information on how and when to mark sections of code as critical.